'''
Created on 2012-1-21
@author: laibiwei
'''
import threading
import sys
from PyQt4 import QtGui,QtCore
from ui import tcptestorui
from ui import tcptabui
from texas_client import texas_client
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
import ConfigParser


import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


from xml.etree import ElementTree

class tcptestor_dlg(object):
    def __init__(self):
        self.logontokens = "1,2,3,4,5,6,7,8"
        try:
            config = ConfigParser.ConfigParser()                         
            config.readfp(open('config.ini'))            
            self.address = str(config.get("gameserver","address"))
            self.logontokens = str(config.get("gameserver", "logontokens"))                                    
        except:
            self.address = "117.135.132.62:8000"
            self.logontokens = "1,2,3,4,5,6,7,8"
        
        self.uimod = tcptestorui.tcptab_manager(self)
        logonlist = self.logontokens.split(",")
        self.clientlist = []
        for item in logonlist:
            self.clientlist.append(texas_client(item, 0))
            
        for item in self.clientlist: 
            self.uimod.add_new_connection(self.address,item)
            
        for item in self.clientlist: 
            item.logon()

    def ping(self):
        for item in self.clientlist: 
            item.ping()

def sayhello(dlg):
    dlg.ping()
    t = threading.Timer(30.0, sayhello, [dlg])
    t.start()
      
def main():
    class logic_thread(QtCore.QThread):
        def __init__(self, parent=None):  
            QtCore.QThread.__init__(self, parent)
   
        def run(self): #Overwrite run() method, put what you want the thread do here
            tcptabui.reactor.run()
    try:
        datastr = str("<success id='YWx8se'><uid>113239</uid><deskid>-1</deskid><sgamestate id='ScMR_")
        pos1 = datastr.find("<success>")
        pos2 = datastr.find("</success>")
        if (pos1!=-1 and pos2!=-1):
            xmldata = datastr[pos1:pos2+"</success>".__len__()]
            root = ElementTree.fromstring(xmldata)
            lst_node = root.getiterator("success")
            for node in lst_node:
                uid_node = node.getiterator("uid")
                for unode in uid_node:                
                    text = unode.text     
                    break
                break
    except:
        pass  
                
    logicthread=logic_thread()
    logicthread.start()   
    
    
    app = QtGui.QApplication(sys.argv)
    dlg = tcptestor_dlg()
    
    t = threading.Timer(5.0, sayhello, [dlg])
    t.start()
                  
    app.exec_()  
    
    
    
        
    
main()
